home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: driftwood.cray.com!jvb
- From: jvb@cray.com (Jeff Boyd)
- Subject: overload + operator question
- Message-ID: <1996Mar14.133124.12847@driftwood.cray.com>
- Nntp-Posting-Host: hickory024
- Organization: Cray Research, Inc.
- Date: 14 Mar 96 13:31:24 CST
-
- I have a question regarding an overloaded + (or *) operator. The code segment
- below gives the following message, as expected:
-
- "coord-add.C", line 38: Error: The operation "int + coord" is illegal.
-
- but by making the class + class operator a 'friend' all compiles fine and gives
- expected results. Why? Happens with: g++, Sparc C++, Cfront, Cray.
- Please send any answers to me as I don't have regular news access. Thanks.
-
- Code:
-
- #include <iostream.h>
-
- class coord{
- int x;
- public:
- coord():x(0){}
- coord(int i):x(i){}
- void get_x(int &i){i = x;}
- // by making next operator a 'friend', then an operation
- // such as: 'int + coord' becomes legal
- coord operator+(coord ob2); // ob + ob
- };
-
- // overload + relative to coord class
- coord coord::operator + (coord ob2)
- {
- coord temp;
- temp.x = x + ob2.x;
- return temp;
- }
-
-
- main()
- {
- coord o1(10),o2(3),o3;
- int x;
- o3 = o2 + 100;
- // will be flagged as 'illegal' unless friend ob + ob defined:
- o3 = 100 + o2;
- o3.get_x(x);
- }
-
- ------
- Jeff
- jvb@cray.com
-